package com.yxzr.youyou;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.yxzr.youyou.adapter.ClassificationAdapter;
import com.yxzr.youyou.adapter.ComicTypeAdapter;
import com.yxzr.youyou.adapter.CommentAdapter;
import com.yxzr.youyou.adapter.MovieOneRecyclerViewAdapter;
import com.yxzr.youyou.adapter.PictureRecyclerViewAdapter;
import com.yxzr.youyou.adapter.VideoDetailAdapter;
import com.yxzr.youyou.base.BaseActivity;
import com.yxzr.youyou.bean.CommentBean;
import com.yxzr.youyou.bean.MovieBean;
import com.yxzr.youyou.bean.MovieDetailBean;
import com.yxzr.youyou.bean.UserInfoBean;
import com.yxzr.youyou.retrofit.BaseObserver;
import com.yxzr.youyou.retrofit.DataUrl;
import com.yxzr.youyou.retrofit.RequestUtil;
import com.yxzr.youyou.utils.NullStringToEmptyAdapterFactory;
import com.yxzr.youyou.utils.RecyclerItemDecoration;
import com.yxzr.youyou.utils.SharedPreferencesHelper;
import com.yxzr.youyou.utils.StatusUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import jp.wasabeef.glide.transformations.CropCircleTransformation;

public class VideoDetailActivity extends BaseActivity {
    private ImageView mVideoDetailThumb,mVideoDetailAvatar;
    private TextView mVideoDetailName,mVideoDetailUserName,mVideoDetailScore,mVideoDetailStime,mVideoDetailDirector,mVideoDetailPerformer,
            mVideoDetailAddress, mVideoDetailType,mVideoDetailPlot,mVideoDetailTitle,mVideoDetailZuiXin,comment_tv_num;
    private RecyclerView mRecyclerView,mRecyclerViewPlay,mRecyclerViewComment;
    private RelativeLayout videodetail_rel_login,videodetail_rel_comment;
    private Button mVideoDetailBtn1,mVideoDetailBtn2,videodetail_btn_vip;
    private VideoDetailAdapter adapter;
    private CommentAdapter adapterComment;
    private List<MovieDetailBean.DataBean> list = new ArrayList<>();
    private List<CommentBean.DataBean> listComment = new ArrayList<>();
    private StatusUtils statusUtils;
    private SharedPreferencesHelper sp;
    private String id = "";
    private int index = 0;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_videodetail);
        id = getIntent().getStringExtra("id");
        index = getIntent().getIntExtra("index",0);
        sp = new SharedPreferencesHelper(this,"logindata");
        statusUtils = new StatusUtils(this);
        setTitleWithBack();
        initView();
    }

    private void initView() {
        mVideoDetailThumb = findViewById(R.id.videodetail_img);
        mVideoDetailAvatar = findViewById(R.id.videodetail_avatar);
        mRecyclerView = findViewById(R.id.videodetail_rv);
        mRecyclerViewPlay = findViewById(R.id.videodetail_rv_play);
        mRecyclerViewComment = findViewById(R.id.comment_rv);
        comment_tv_num = findViewById(R.id.comment_tv_num);
        mVideoDetailBtn1 = findViewById(R.id.videodetail_btn_m);
        mVideoDetailBtn2 = findViewById(R.id.videodetail_btn_share);
        mVideoDetailName = findViewById(R.id.videodetail_tv_name);
        mVideoDetailUserName = findViewById(R.id.videodetail_username);
        videodetail_rel_comment = findViewById(R.id.videodetail_rel_comment);
        videodetail_rel_login = findViewById(R.id.videodetail_rel_login);
        mVideoDetailScore = findViewById(R.id.videodetail_tv_score);
        mVideoDetailStime = findViewById(R.id.videodetail_tv_stime);
        mVideoDetailDirector = findViewById(R.id.videodetail_tv_director);
        mVideoDetailPerformer = findViewById(R.id.videodetail_tv_performer);
        mVideoDetailAddress = findViewById(R.id.videodetail_tv_address);
        mVideoDetailType = findViewById(R.id.videodetail_tv_type);
        mVideoDetailPlot = findViewById(R.id.videodetail_tv_plot);
        mVideoDetailTitle = findViewById(R.id.videodetail_tv_title);
        mVideoDetailZuiXin = findViewById(R.id.videodetail_tv_zuixin);
        videodetail_btn_vip = findViewById(R.id.videodetail_btn_vip);

        videodetail_btn_vip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (statusUtils.isLogin()){
                    Intent intent = new Intent(VideoDetailActivity.this,RechargeActivity.class);
                    startActivity(intent);
                }else {
                    statusUtils.toLoginActivity();
                }

            }
        });


        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,3);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        mRecyclerView.addItemDecoration(new RecyclerItemDecoration(20,3));
        mRecyclerView.setNestedScrollingEnabled(false);

        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this,4);
        mRecyclerViewPlay.setLayoutManager(gridLayoutManager1);
        mRecyclerViewPlay.addItemDecoration(new RecyclerItemDecoration(28,4));
        adapter = new VideoDetailAdapter(VideoDetailActivity.this);
        mRecyclerViewPlay.setNestedScrollingEnabled(false);
        mRecyclerViewPlay.setAdapter(adapter);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerViewComment.setLayoutManager(linearLayoutManager);
        mRecyclerViewComment.addItemDecoration(new RecyclerItemDecoration(2,1));
        adapterComment = new CommentAdapter(this);
        mRecyclerViewComment.setAdapter(adapterComment);

        videodetail_rel_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!statusUtils.isLogin()){
                    statusUtils.toLoginActivity();
                }
            }
        });
        videodetail_rel_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(VideoDetailActivity.this, CommentActivity.class);
                intent.putExtra("bean", (Serializable) list);
                startActivity(intent);
            }
        });
        adapter.setOnClickListener(new ComicTypeAdapter.OnClickListener() {
            @Override
            public void onClick(int position) {
                adapter.setSelectIndex(position);
                Intent intent = new Intent(VideoDetailActivity.this, MoviePlayActivity.class);
                intent.putExtra("url",list.get(0).getMovie_url().get(position).getLianjie());
                intent.putExtra("bean", (Serializable) list);
                startActivity(intent);
//                if (index == 0){
//                    adapter.setSelectIndex(position);
//                    Intent intent = new Intent(VideoDetailActivity.this, MoviePlayActivity.class);
//                    intent.putExtra("url",list.get(0).getMovie_url().get(position).getLianjie());
//                    intent.putExtra("bean", (Serializable) list);
//                    startActivity(intent);
//                }else {
//
//                }

            }
        });

        getUserInfo();
    }

    private void getUserInfo(){
        RequestUtil.getInstence().API().getUserInfo((String) sp.getSharedPreference("token",""))
                .subscribeOn(Schedulers.io()) // 在子线程中进行Http访问
                .observeOn(AndroidSchedulers.mainThread()) // UI线程处理返回接口
                .subscribe(new BaseObserver(this,true){
                    @Override
                    protected void onSuccees(String t) {
                        Gson gson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
                        UserInfoBean bean = gson.fromJson(t,UserInfoBean.class);

                        if ("0".equals(bean.getData().getVip())){
                            videodetail_btn_vip.setText("开通会员");
                            videodetail_btn_vip.setEnabled(true);
                        }else {
                            videodetail_btn_vip.setText("VIP会员");
                            videodetail_btn_vip.setEnabled(false);
                        }
                    }

                    @Override
                    protected void onFail(int error_code) {

                    }

                    @Override
                    protected void onComp() {

                    }

                    @Override
                    protected void onErr(Throwable e) {

                    }
                });
    }

    private void getCommentList(){
        RequestUtil.getInstence().API().getCommentList((String) sp.getSharedPreference("token",""),list.get(0).getMovie_id(),"1")
                .subscribeOn(Schedulers.io()) // 在子线程中进行Http访问
                .observeOn(AndroidSchedulers.mainThread()) // UI线程处理返回接口
                .subscribe(new BaseObserver(this,true){
                    @Override
                    protected void onSuccees(String t) {
                        Gson gson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
                        CommentBean bean = gson.fromJson(t,CommentBean.class);
                        if (bean.getData() != null){
                            listComment.clear();
                            adapterComment.clearList();
                            if (bean.getData().size() >= 3){
                                for (int i = 0;i < 3;i++){
                                    listComment.add(bean.getData().get(i));
                                }
                            }else if (bean.getData().size() < 3 && bean.getData().size() > 0){
                                for (int i = 0;i < bean.getData().size();i++){
                                    listComment.add(bean.getData().get(i));
                                }
                            }
                            adapterComment.addList(listComment);
                        }
                    }

                    @Override
                    protected void onFail(int error_code) {

                    }

                    @Override
                    protected void onComp() {

                    }

                    @Override
                    protected void onErr(Throwable e) {

                    }
                });
    }


    private void initData(){
        RequestUtil.getInstence().API().movieDetail(id)
                .subscribeOn(Schedulers.io()) // 在子线程中进行Http访问
                .observeOn(AndroidSchedulers.mainThread()) // UI线程处理返回接口
                .subscribe(new BaseObserver(this,true){
                    @Override
                    protected void onSuccees(String t) {
                        Gson gson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
                        MovieDetailBean bean = gson.fromJson(t,MovieDetailBean.class);
                        comment_tv_num.setText("评论("+bean.getData().get(0).getCommentCount()+")");
                        list = bean.getData();
                        adapter.clearList();
                        adapter.addList(bean.getData().get(0).getMovie_url());
                        mRecyclerView.setAdapter(new PictureRecyclerViewAdapter(VideoDetailActivity.this,bean.getData().get(0).getZuixin()));

                        adapter.setIndex(bean.getData().get(0).getIs_houtai_add());

                        setViewData(bean);
                    }

                    @Override
                    protected void onFail(int error_code) {

                    }

                    @Override
                    protected void onComp() {
                        getCommentList();
                    }

                    @Override
                    protected void onErr(Throwable e) {

                    }
                });
    }

    public void setViewData(MovieDetailBean viewData) {
        if (TextUtils.isEmpty(viewData.getData().get(0).getPath())){
            Glide.with(this)
                    .setDefaultRequestOptions(
                            new RequestOptions()
                                    .frame(3000000)
                                    .centerCrop()
                                    .error(R.drawable.dialog_loading)
                                    .placeholder(R.drawable.dialog_loading))
                    .load(viewData.getData().get(0).getUrl())
                    .into(mVideoDetailThumb);
        }else {
            Glide.with(this)
                    .setDefaultRequestOptions(
                            new RequestOptions()
                                    .frame(3000000)
                                    .centerCrop()
                                    .error(R.drawable.dialog_loading)
                                    .placeholder(R.drawable.dialog_loading))
                    .load(DataUrl.imgUrl+viewData.getData().get(0).getPath())
                    .into(mVideoDetailThumb);
        }


        mVideoDetailName.setText(viewData.getData().get(0).getTitle());
        mVideoDetailScore.setText(viewData.getData().get(0).getRating());
        mVideoDetailStime.setText("上映时间："+viewData.getData().get(0).getYear());
        mVideoDetailDirector.setText("导演："+viewData.getData().get(0).getDirectors());
        mVideoDetailPerformer.setText("演员："+viewData.getData().get(0).getActors());
        mVideoDetailAddress.setText("地区："+viewData.getData().get(0).getArea());
        mVideoDetailType.setText("类型："+viewData.getData().get(0).getCtitle());
        mVideoDetailPlot.setText(Html.fromHtml(viewData.getData().get(0).getContent()));
        mVideoDetailTitle.setText(viewData.getData().get(0).getCtitle());
        mVideoDetailZuiXin.setText("最新"+viewData.getData().get(0).getCtitle());

    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
        if (statusUtils.isLogin()){
            Glide.with(this)
                    .setDefaultRequestOptions(
                            new RequestOptions()
                                    .frame(1000000)
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .centerCrop()
                                    .error(R.mipmap.default_avatar)
                                    .placeholder(R.mipmap.default_avatar))
                    .load(DataUrl.imgUrl+(String) sp.getSharedPreference("avatar",""))
                    .apply(RequestOptions.bitmapTransform(new CropCircleTransformation()))
                    .into(mVideoDetailAvatar);

            mVideoDetailUserName.setText((String) sp.getSharedPreference("username",""));
        }
    }
}
